package com.ruoyi.web.controller.api;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.domain.model.UserCourse;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DateUtil;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.MimeTypeUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.domain.SysCourse;
import com.ruoyi.system.domain.SysStudent;
import com.ruoyi.system.mapper.SysStudentMapper;
import com.ruoyi.system.mapper.SysTestRecordMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.mapper.SysWordLearningProgressMapper;
import com.ruoyi.system.service.ISysCourseService;
import com.ruoyi.system.service.ISysStudentService;
import com.ruoyi.system.service.ISysUserService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import io.swagger.annotations.Example;
import io.swagger.annotations.ExampleProperty;

@Api(tags = "用户个人信息")
@RestController
@RequestMapping("/api/profile")
public class ApiProfileController extends BaseController {

    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private ISysStudentService sysStudentService;
    @Autowired
    private ISysCourseService sysCourseService;

    @Autowired
    private TokenService tokenService;
    @Autowired
    private SysWordLearningProgressMapper sysWordLearningProgressMapper;
    @Autowired
    private SysStudentMapper sysStudentMapper;
    @Autowired
    private SysTestRecordMapper sysTestRecordMapper;

    /**
     * 上传用户头像
     */
    @ApiOperation("上传用户头像")
    @Log(title = "用户头像", businessType = BusinessType.UPDATE)
    @PostMapping("/avatar")
    public AjaxResult avatar(@RequestParam(value = "avatarfile", required = false) MultipartFile file,
                                  @RequestParam(value = "avatarUrl", required = false) String avatarUrl) throws Exception {
        if (file != null && !file.isEmpty()) {
            // 处理本地图片上传
            LoginUser loginUser = SecurityUtils.getLoginUser();
            String avatar = FileUploadUtils.upload(RuoYiConfig.getAvatarPath(), file, MimeTypeUtils.IMAGE_EXTENSION);
            String fullAvatarUrl = RuoYiConfig.getServerUrl() + avatar;
            return updateStudentAvatar(loginUser, fullAvatarUrl);
        } else if (avatarUrl != null && !avatarUrl.trim().isEmpty()) {
            // 处理网络图片URL
            LoginUser loginUser = SecurityUtils.getLoginUser();
            // 这里可以添加URL合法性验证
            if (!avatarUrl.startsWith("http://") && !avatarUrl.startsWith("https://")) {
                return error("无效的图片URL地址");
            }
            return updateStudentAvatar(loginUser, avatarUrl);
        }
        return error("请提供有效的图片文件或图片URL地址");
    }

    /**
     * 更新用户头像信息
     */
    private AjaxResult updateStudentAvatar(LoginUser loginUser, String avatar) {
        if (sysStudentService.updateAvatar(loginUser.getUsername(), avatar)) {
            AjaxResult ajax = AjaxResult.success();
            // 添加域名前缀，确保返回完整的URL
            ajax.put("imgUrl", avatar);
            // 更新缓存用户头像
            loginUser.getUser().setAvatar(avatar);
            // 刷新用户缓存
            tokenService.setLoginUser(loginUser);
            return ajax;
        }
        return error("更新头像失败，请联系管理员");
    }

    /**
     * 更新用户个人基本信息
     */
    @ApiOperation("更新用户个人基本信息")
    @Log(title = "个人信息", businessType = BusinessType.UPDATE)
    @PostMapping("/update")
    public AjaxResult updateBasicInfo(@RequestBody Map<String, String> params) {
        // 获取当前登录用户信息
        LoginUser loginUser = SecurityUtils.getLoginUser();

        // 更新学生信息
        SysStudent sysStudent = sysStudentService.selectById(loginUser.getStudentId());
        if (params.containsKey("schoolName")) {
        	sysStudent.setSchoolName(params.get("schoolName"));
        }
        if (params.containsKey("grade")) {
        	sysStudent.setGrade(params.get("grade"));
        }
        if (params.containsKey("realName")) {
        	sysStudent.setRealName(params.get("realName"));
        }
        if (params.containsKey("sex")) {
        	sysStudent.setSex(params.get("sex")); // 性别信息
        }
        if (params.containsKey("phoneNumber")) {
            String phoneNumber = params.get("phoneNumber");
            sysStudent.setPhonenumber(phoneNumber);
            // 检查手机号是否已被其他用户使用
            if (!sysStudentService.checkPhoneUnique(sysStudent)) {
                return error("更新失败，该手机号已被使用");
            }
        }
        sysStudentService.updateProfile(sysStudent);

        // 更新用户信息
        SysUser user = loginUser.getUser();
        if (params.containsKey("schoolName")) {
            user.setSchoolName(params.get("schoolName"));
        }
        if (params.containsKey("grade")) {
            user.setGrade(params.get("grade"));
        }
        if (params.containsKey("realName")) {
            user.setRealName(params.get("realName"));
        }
        if (params.containsKey("sex")) {
            user.setSex(params.get("sex")); // 性别信息
        }
        if (params.containsKey("phoneNumber")) {
            String phoneNumber = params.get("phoneNumber");
            user.setPhonenumber(phoneNumber);
            // 检查手机号是否已被其他用户使用
            if (!userService.checkPhoneUnique(user)) {
                return error("更新失败，该手机号已被使用");
            }
        }

        if (userService.updateUserProfile(user) > 0) {
            // 更新缓存用户信息
            tokenService.setLoginUser(loginUser);
            return success();
        }
        return error("更新个人信息失败，请联系管理员");
    }

    /**
     * 获取当前登录用户的课程列表
     */
    @ApiOperation("获取当前登录用户的课程列表")
    @GetMapping("/courses")
    public AjaxResult getCourses() {
        // 获取当前登录用户信息
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long studentId = loginUser.getStudentId();
        
        // 这里暂时返回模拟数据，后续需要从数据库获取实际的课程数据
        List<SysCourse> listEntity = sysCourseService.listByStudentId(studentId);
        List<UserCourse> courses = new ArrayList<UserCourse>();
        for(SysCourse sysCourse : listEntity) {

            UserCourse course = new UserCourse();
            course.setCourseId(sysCourse.getCourseId());
            course.setCourseName(sysCourse.getCourseName());
            course.setDescription("--");
            course.setStatus(UserCourse.STATUS_FINISHED);
            course.setStartTime(new Date());
            course.setFinishTime(new Date());
            courses.add(course);
        }
        
        return AjaxResult.success(courses);
    }

    /**
     * 获取当前登录用户的个人信息
     */
    @ApiOperation(
        value = "获取当前登录用户的个人信息",
        notes = "获取当前登录用户的详细信息，包括基本信息、头像、登录信息等",
        response = AjaxResult.class,
        responseReference = "{\"成功\":{\"code\":200,\"msg\":\"操作成功\",\"data\":{\"avatar\":\"http://example.com/avatar.jpg\",\"nickName\":\"张三\",\"role\":\"学员\",\"schoolName\":\"示例学校\",\"grade\":\"高一\",\"realName\":\"张三\",\"sex\":\"0\",\"phoneNumber\":\"13800138000\",\"lastLoginTime\":\"2024-01-01 12:00:00\",\"loginLocation\":\"XX省XX市\",\"loginIp\":\"127.0.0.1\",\"loginCount\":1}},\"失败\":{\"code\":401,\"msg\":\"未登录或登录已过期\"}}"
    )
    @ApiResponses({
        @ApiResponse(code = 200, message = "操作成功", response = AjaxResult.class, examples = @Example({
            @ExampleProperty(mediaType = "application/json", value = "{\"code\":200,\"msg\":\"操作成功\",\"data\":{\"avatar\":\"http://example.com/avatar.jpg\",\"nickName\":\"张三\",\"role\":\"学员\",\"schoolName\":\"示例学校\",\"grade\":\"高一\",\"realName\":\"张三\",\"sex\":\"0\",\"phoneNumber\":\"13800138000\",\"lastLoginTime\":\"2024-01-01 12:00:00\",\"loginLocation\":\"XX省XX市\",\"loginIp\":\"127.0.0.1\",\"loginCount\":1}}")
        })),
        @ApiResponse(code = 401, message = "未登录或登录已过期")
    })
    @GetMapping("/info")
    public AjaxResult info() {
        // 获取当前登录用户信息
        LoginUser loginUser = SecurityUtils.getLoginUser();
        
        Map<String, Object> profile = new HashMap<>();
        
        Long studentId = loginUser.getStudentId();
        SysStudent sysStudent = sysStudentMapper.selectById(studentId);
        Date now = new Date();
        
        // 添加域名前缀，确保返回完整的URL
        profile.put("avatar", sysStudent.getAvatar()); // 头像
        profile.put("nickName", sysStudent.getStudentName()); // 昵称
        profile.put("role", "学员"); // 身份，默认为学员
        profile.put("schoolName", sysStudent.getSchoolName() != null ? sysStudent.getSchoolName() : "学校名称"); // 学校名称
        profile.put("grade", sysStudent.getGrade()); // 年级
        profile.put("realName", sysStudent.getRealName() != null ? sysStudent.getRealName() : ""); // 真实姓名
        profile.put("sex", sysStudent.getSex()); // 性别
        profile.put("phoneNumber", sysStudent.getPhonenumber()); // 联系方式
        profile.put("createTime", sysStudent.getCreateTime() != null ? sysStudent.getCreateTime().getTime() : null); // 账号注册时间，转换为时间戳
        
        // 登录相关信息
        profile.put("lastLoginTime", loginUser.getLoginTime()); // 最后登录时间
        profile.put("loginCount", sysUserMapper.countLoginTimes(loginUser.getUsername())); // 登录次数
        
        // 学习相关统计信息
        profile.put("totalStudyDays", (now.getTime() - sysStudent.getCreateTime().getTime() + 86400000 - 1) / 86400000); // 累计学习时间（天）
        String today = DateUtil.getYYYY_MM_DD(new Date());
        profile.put("todayMasteredWords", sysWordLearningProgressMapper.sumStudyed(studentId, null, null, today, today)); // 今日掌握单词数
        profile.put("totalMasteredWords", sysWordLearningProgressMapper.sumStudyed(studentId, null, null, null, null)); // 所有学习单词总数
        profile.put("perfectScoreTimes", sysTestRecordMapper.countFULL(studentId)); // 获得满分次数
        profile.put("vipExpireTime", DateUtil.parseYYYY_MM_dd_HH_mm_ss(sysStudent.getExpireTime() + " 23:59:59").getTime()); // 会员过期时间
        
        profile.put("correctWordTipSeconds", sysStudent.getCorrectWordTipSeconds()); // 正确单词提示秒数
        profile.put("dictationDuration", sysStudent.getDictationDuration()); // 听写时长（单位：秒）
        
        // 在Java中，数字字面量如果超过int的最大值(2147483647)时，需要加L后缀表示这是一个long类型
        // 1767252720000这个数字超过了int的范围，所以需要加L，否则会报编译错误
        
        return AjaxResult.success(profile);
    }
}